import axios from 'axios'
const API_ROOT = window.api_root + "files";
let folder = '';
const setRootFolder = (val) => {
    folder = val;
}
const fetchFiles = async () => {
    try {
        const response = await axios.get(`${API_ROOT}/${folder}/list`)
        return response  // 假设返回的数据是一个数组
    } catch (error) {
        console.error('获取文件列表失败:', error)
        return [];
    }
}

// 上传单个文件
const uploadFile = async (file) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await axios.post(`${API_ROOT}/${folder}/upload`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });

        if (response.data.success) {
            return { success: true, name: file.name };
        } else {
            return { success: false, name: file.name, error: response.data.message };
        }
    } catch (error) {
        console.error(`上传文件 "${file.name}" 出错:`, error);
        return { success: false, name: file.name, error: '网络错误或服务器错误' };
    }
};

const deleteFile = async (name) => {
    try {
        const response = await axios.delete(`${API_ROOT}/${folder}/delete/${name}`)
        return response.data;
    } catch (error) {
        return "删除失败";
    }
}
export default {
    setRootFolder, fetchFiles, uploadFile, deleteFile
}